package com.miku.blog.utils;

import com.miku.blog.domain.*;
import com.miku.blog.domain.pojo.IpAddressesDetail;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author shkstart
 * @create ${}YEAR-05-26 2:03
 */
public class UserUtils {



    public static void setLoginInfoIpDetail(UserLoginInfo loginInfo, IpAddressesDetail ipAddressesDetail, UserAgentParseUtils.UserAgentParse userAgent){
        String ipLocation = getIpLocation(ipAddressesDetail);
        loginInfo.setIpAddr(ipAddressesDetail.getIp())
                .setIpSource(ipLocation != null ? ipLocation : loginInfo.getIpSource());

        if (Objects.nonNull(userAgent)){
            String systemName = userAgent.getSystemName();
            String browserName = userAgent.getBrowserName();

            String os = loginInfo.getOs();
            String browser = loginInfo.getBrowser();
            if (!StringUtils.hasText(os) || !StringUtils.hasText(browser)){
                loginInfo.setOs(systemName)
                        .setBrowser(browserName);
            }else {
                loginInfo.setOs("UNKNOWN".equalsIgnoreCase(systemName) ? os : systemName)
                        .setBrowser("UNKNOWN".equalsIgnoreCase(browserName) ? browser : browserName);
            }
        }
    }



    public static String getIpLocation(IpAddressesDetail addressesDetail){
        String location = null;
        List<Map<String, Object>> data = addressesDetail.getData();
        if (Objects.nonNull(data)) {
            Map<String, Object> map = data.get(0);
            location = map.get("location").toString();
        }
        return location;
    }


}
